import router from '../router';
import store from '../store'

let getRouter; //用来获取后台拿到的路由
const login = "/Login";
router.beforeEach((to, from, next) => {
  if (to.path === login) {
    next();
  }
  if (!to.meta.requireAuth) {//校验token是否存在,不存在拦截
    const userInfo = sessionStorage.getItem('userInfo');
    if (!userInfo || userInfo === null || userInfo === "" || userInfo === "{}") {
      if (from.path !== login) {
        next(login);
      }
    }
    else {
      if (from.path === login) {
        next();
      }
      else {
        if (getRouter) {
          next();
        }
        else {
          const list = JSON.parse(sessionStorage.getItem('list'));
          getRouter = list; //假装模拟后台请求得到的路由数据
          if (!list || list.length === 0 || list === null || list === "") {
            next(login);
          }
          else {
            store.dispatch("filterRouter", list).then((obj) => {
              store.dispatch("filterMenus", list).then(() => {
                next({...to, replace: true});
              });
            });
          }
        }
      }
    }
  }
});
